package dmitrygusev.ratings.services.renders;

import java.util.List;

import dmitrygusev.nanoxml.XMLUtils;
import dmitrygusev.nanoxml.lite.XMLElement;
import dmitrygusev.ratings.model.Movie;
import dmitrygusev.ratings.model.Rating;

public class ResultsXmlRender {

	public XMLElement render(List<Movie> movies) {
		XMLElement moviesXml = XMLUtils.createElement("movies");
		
		if (movies != null && ! movies.isEmpty()) {
			for (Movie movie : movies) {
				XMLElement movieXml = XMLUtils.createChildElement(moviesXml, "movie");
				
				XMLUtils.createChildElement(movieXml, "title").setContent(movie.getTitle());
				if (movie.isTitle2Available()) {
					XMLUtils.createChildElement(movieXml, "title2").setContent(movie.getTitle2());
				}
				XMLUtils.createChildElement(movieXml, "year").setContent(movie.getYear());
				XMLUtils.createChildElement(movieXml, "source").setContent(movie.getSource());
				XMLUtils.createChildElement(movieXml, "code").setContent(movie.getCode());
				XMLUtils.createChildElement(movieXml, "url").setContent(movie.getUrl());
				XMLUtils.createChildElement(movieXml, "comments").setContent(movie.getCommentsCount());
				XMLUtils.createChildElement(movieXml, "cover").setContent(movie.getCoverPicture());
				
				for (Rating rating : movie.getRatings()) {
					XMLElement ratingElement = XMLUtils.createChildElement(movieXml, "rating");
					ratingElement.setContent(rating.getValue());
					if (rating.getVotes() != null) {
						ratingElement.setAttribute("votes", rating.getVotes());
					}
					if (rating.getType() != null) {
						ratingElement.setAttribute("type", rating.getType());
					}
				}
			}
		}
		
		return moviesXml;
	}

}
